package com.fdb.efp.batch.service.impl.basicfn;

import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.efp.batch.service.facade.basicfn.FailureCooprOrgStatusService;
import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.service.facade.AstSysMessageService;
import com.fdb.efp.console.service.facade.SRoleService;
import com.fdb.efp.console.service.vo.AstSysMessageVO;
import com.fdb.efp.console.service.vo.SRoleVO;
import com.fdb.efp.riskm.common.RiskColltConstant;
import com.fdb.efp.riskm.service.facade.CooprOrgInfoService;
import com.fdb.efp.riskm.service.vo.CooprOrgInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 需求编号【2019D0509】
 *
 * @author qiuyf
 * @version 0.1 初始为0.1,后续变更则修改
 * @since 2019/12/25 17:04
 */
@Service("failureCooprOrgStatusService")
public class FailureCooprOrgStatusServiceImpl implements FailureCooprOrgStatusService {

    private Logger logger = LoggerFactory.getLogger("FailureCooprOrgStatusServiceImpl");

    @Autowired
    @Qualifier("cooprOrgInfoService")
    private CooprOrgInfoService cooprOrgInfoService;

    @Autowired
    @Qualifier("sRoleService")
    private SRoleService sRoleService;

    @Autowired
    @Qualifier("astSysMessageService")
    private AstSysMessageService astSysMessageService;


    @Override
    public Boolean inValidCooprOrgrOverCooprEndDt() {
        LocalDate nowDate = LocalDate.now();
        logger.info("======>终止合作日期到期的合作机构信息批次任务开始执行<======" + nowDate.toString());
        //获取昨天合作到期的合作机构信息
        List<CooprOrgInfoVO> allCooprOrgOverCooprDtList = Optional.ofNullable(cooprOrgInfoService.getAllCooprOrgOverCooprDt()).orElse(new ArrayList<>());
        int allNum = allCooprOrgOverCooprDtList.size();
        if(allNum > 0){
            logger.info("======>终止合作日期到期的合作机构信息开始，当前日期为:<======" + nowDate);
            int num = cooprOrgInfoService.inValidCooprOrgOverCooprDt();
            logger.info("======>终止合作日期到期的合作机构信息结束，终止的合作方信息条数为:<======" +num);

            if(num > 0){
                logger.info("======>获取外催角色并新增公告信息开始<======");
                SRoleVO sRoleVO = new SRoleVO();
                //目前以外催模糊查询角色信息 @date 2019/12/25
                sRoleVO.setRoleName("外催");
                List<SRoleVO> sRoleVOList = sRoleService.queryAllValidRole(sRoleVO);
                if(Objects.nonNull(sRoleVOList) && sRoleVOList.size() > 0){
                    String roleCodes = sRoleVOList.stream().map(SRoleVO::getRoleCode).collect(Collectors.joining(","));
                    // roleCodes = roleCodes.substring(0, roleCodes.length() -1);

                    StringBuffer title = new StringBuffer().append("昨天共有").append(allNum).append("个合作机构合作到期，").append("已失效").append(num).append("个");
                    StringBuffer message = new StringBuffer().append("昨天共有").append(allNum).append("个合作机构合作到期，").append("已失效").append(num).append("个");

                    //当合作机构到期总数不等于已更新为"终止"的数量时，再查询获取得到无法更新失效的合作机构信息
                    if(allNum != num){
                        message.append("，因合作机构存在未处理完成的案件或存在未处理完成的案件占比，无法将合作机构的合作状态更新为终止，有")
                                .append(allNum - num).append("个。").append("\n");
                        List<CooprOrgInfoVO> cooprOrgInfoList = Optional.ofNullable(cooprOrgInfoService.getAllCooprOrgOverCooprDt()).orElse(new ArrayList<>());
                        if(cooprOrgInfoList.size() > 0){
                            dealMessageHadCooprOrg(cooprOrgInfoList, message);
                        }
                    }
                    AstSysMessageVO astSysMessageVO = new AstSysMessageVO();
                    astSysMessageVO.setTitle(title.toString());
                    astSysMessageVO.setMess(message.toString());
                    astSysMessageVO.setInputdate(nowDate.toString());
                    astSysMessageVO.setSenddate(nowDate.toString());
                    astSysMessageVO.setSenderId(BaseConstant.ADMIN);
                    astSysMessageVO.setRoleIds(roleCodes);
                    astSysMessageVO.setMesType(ConsoleConstant.MES_TYPE_1);
                    int insNum = astSysMessageService.insertAstSysMessage(astSysMessageVO);
                    if(insNum != 1){
                        logger.error("有终止合作机构信息，新增公告告知拥有外催角色的用户，新增失败！");
                    }
                }else{
                    logger.error("通过关键字【外催】模糊查询到的角色信息为空，无法新增公告！");
                }
            }

        }
        return true;
    }

    /**
     * 拼接外催机构信息
     * @param cooprOrgInfoList 外催机构信息（已到期，未失效的）
     * @param message 公告信息
     */
    private void dealMessageHadCooprOrg(List<CooprOrgInfoVO> cooprOrgInfoList, StringBuffer message){
        //处理委外机构
        List<CooprOrgInfoVO> outsList = cooprOrgInfoList.stream()
                .filter(cooprOrgInfoVO -> {
                    return RiskColltConstant.COOPR_ORG_TYPE_001.equals(cooprOrgInfoVO.getCooprOrgType());
                })
                .collect(Collectors.toList());
        if(Objects.nonNull(outsList) && outsList.size() > 0){
            message.append("\t").append("委外机构有").append(outsList.size()).append("个，分别是：").append("\n");
            dealCooprOrgInfo(outsList, message);
        }
        //处理律师事务所
        List<CooprOrgInfoVO> lawsList = cooprOrgInfoList.stream()
                .filter(cooprOrgInfoVO -> {
                    return RiskColltConstant.COOPR_ORG_TYPE_002.equals(cooprOrgInfoVO.getCooprOrgType());
                })
                .collect(Collectors.toList());
        if(Objects.nonNull(lawsList) && lawsList.size() > 0){
            message.append("\t").append("律师事务所有").append(lawsList.size()).append("个，分别是：").append("\n");
            dealCooprOrgInfo(lawsList, message);
        }
        //处理风险代理机构
        List<CooprOrgInfoVO> riskList = cooprOrgInfoList.stream()
                .filter(cooprOrgInfoVO -> {
                    return RiskColltConstant.COOPR_ORG_TYPE_003.equals(cooprOrgInfoVO.getCooprOrgType());
                })
                .collect(Collectors.toList());
        if(Objects.nonNull(riskList) && riskList.size() > 0){
            message.append("\t").append("风险代理机构有").append(riskList.size()).append("个，分别是：").append("\n");
            dealCooprOrgInfo(riskList, message);
        }
    }

    private void dealCooprOrgInfo(List<CooprOrgInfoVO> cooprOrgInfoVOList, StringBuffer message){
        for(CooprOrgInfoVO cooprOrgInfoVO : cooprOrgInfoVOList){
            message.append("\t\t").append("[").append(cooprOrgInfoVO.getCooprOrgNo()).append(" , ").append(cooprOrgInfoVO.getCooprOrgName()).append("]").append("\n");
        }
    }

}
